from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
import json
from django.http import JsonResponse, HttpResponseNotAllowed, HttpResponse, HttpResponseBadRequest

from .models import *
from rest_framework import serializers

from datetime import datetime, timedelta

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetCategoriesList(request):
    user = request.user  # 获取已验证的用户对象

    categories = Category.objects.filter(user=user)

    # 构建数据结构
    category_list = []
    for category in categories:
        # 获取每个Category下的所有SubCategory对象
        subcategories = SubCategory.objects.filter(parent_id=category.id)
        # 将SubCategory转换为字典列表
        subcategory_list = [{"id": subcat.id, "name": subcat.name} for subcat in subcategories]
        # 构建Category字典并添加到列表中
        category_list.append({
            "id": category.id,
            "name": category.name,
            "children": subcategory_list
        })

    return JsonResponse(category_list, safe=False)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetCategoriesInfo(request):
    user = request.user  # 获取已验证的用户对象

    categories = Category.objects.filter(user=user)

    # 构建数据结构
    category_list = []
    for category in categories:
        subcategories = SubCategory.objects.filter(parent_id=category.id)
        clothes = Clothes.objects.filter(sub_category__in=subcategories)
        main_image_url = ""
        if len(clothes)>0 and clothes[0].main_image:
            main_image_url = clothes[0].main_image.url
        category_list.append({
            "id": category.id,
            "name": category.name,
            "count": len(clothes),
            "main_image": main_image_url
        })

    return JsonResponse(category_list, safe=False)

class ClothesBasicSerializer(serializers.ModelSerializer):
    class Meta:
        model = Clothes
        fields = ['id', 'name', 'main_image']

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetClothesBySubCategory(request):
    sub_category_id = request.GET.get('subcategory_id')

    sub_category = SubCategory.objects.get(id=sub_category_id)
    clothes = sub_category.clothes.all()
    serializer = ClothesBasicSerializer(clothes, many=True)
    return Response(serializer.data, status=200)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetClothesByCategory(request):
    category_id = request.GET.get('category_id')
    sub_categories = SubCategory.objects.filter(parent_id=category_id)
    clothes = Clothes.objects.filter(sub_category__in=sub_categories)
    serializer = ClothesBasicSerializer(clothes, many=True)

    return Response(serializer.data, status=200)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetSizeList(request):
    user = request.user  # 获取已验证的用户对象
    size_types = SizeType.objects.filter(user=user)
    # 构建数据结构
    size_list = []
    for size_type in size_types:
        sizes = Size.objects.filter(parent_id=size_type.id)
        # 将SubCategory转换为字典列表
        size_list.append({
            "id": size_type.id,
            "name": size_type.name,
            "children": [{"id": size.id, "name": size.name} for size in sizes]
        })

    return JsonResponse(size_list, safe=False)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetTagList(request):
    user = request.user  # 获取已验证的用户对象
    tag_types = TagType.objects.filter(user=user)
    # 构建数据结构
    tag_list = []
    for tag_type in tag_types:
        tags = Tag.objects.filter(parent_id=tag_type.id)
        # 将SubCategory转换为字典列表
        tag_list.append({
            "id": tag_type.id,
            "name": tag_type.name,
            "children": [{"id": tag.id, "name": tag.name} for tag in tags]
        })

    return JsonResponse(tag_list, safe=False)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetDayRecord(request):
    user = request.user  # 获取已验证的用户对象
    query_date = request.GET.get('date')
    # print(query_date)
    query_date = query_date[0:10]
    if query_date:
        # 将查询参数转换为 datetime 类型
        query_date = datetime.strptime(query_date, '%Y-%m-%d')
        # 过滤日期和用户
        record = Record.objects.filter(user=user, date=query_date).first()  # 添加 user 过滤条件
        if not record:
            return JsonResponse({"clothing": []}, status=200)
        # 构建包含衣服ID和主图片链接的列表
        clothing_data = []
        for clothes in record.clothes.all():
            clothing_data.append({
                "id": clothes.id,
                "name": clothes.name,
                "main_image": clothes.main_image.url if clothes.main_image else None
            })
        record_data = {
            "clothing": clothing_data,
            "date": record.date.strftime("%Y-%m-%d %H:%M:%S"),
            "id": record.id,
        }
        return JsonResponse(record_data)
    else:
        return HttpResponseBadRequest("Invalid date format.")

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetRecordByMonth(request):
    user = request.user  # 获取已验证的用户对象
    year_month = request.GET.get('year_month')
    if year_month:
        try:
            # 将查询参数转换为 datetime 类型
            year, month = map(int, year_month.split('-'))
            start_date = datetime(year, month, 1)
            end_date = start_date.replace(day=28) + timedelta(days=4)  # 确保包含整个月
            end_date = end_date - timedelta(days=end_date.day)

            # 获取该月的所有记录
            records = Record.objects.filter(user=user, date__range=(start_date, end_date))

            date_list = []
            for record in records:
                if record.clothes.count() == 0 and record.suits.count() == 0:
                    continue
                record_date_str = record.date.strftime("%Y-%m-%d")
                date_list.append(record_date_str)

            return Response(date_list)
        except ValueError:
            return Response("Invalid year_month format.", status=400)
    else:
        return Response("Missing year_month parameter.", status=400)
